const AntDesignThemePlugin = require("antd-theme-webpack-plugin");
const path = require("path");
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin');

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

const resolve = (dir) => {
  return path.join(__dirname, dir);
};

module.exports = {
  publicPath: './',

  // 打包生成的生产环境构建文件的目录
  outputDir: "dist",

  // 放置生成的静态资源路径，默认在outputDir
  assetsDir: "static",

  // 指定生成的 index.html 输入路径，默认outputDir
  indexPath: "index.html",

  // 开启 生产环境的 source map?
  productionSourceMap: false,

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // "primary-color": "#1DA57A",
          // "link-color": "#1DA57A",
          // "border-radius-base": "2px"
        },
        javascriptEnabled: true
      }
    }
  },

  configureWebpack: config => {
    // 生产环境相关配置
    if (isProduction) {
        //gzip压缩
        const productionGzipExtensions = ['html', 'js', 'css']
        config.plugins.push(
            new CompressionWebpackPlugin({
                filename: '[path].gz[query]',
                algorithm: 'gzip',
                test: new RegExp(
                    '\\.(' + productionGzipExtensions.join('|') + ')$'
                ),
                threshold: 10240, // 只有大小大于该值的资源会被处理 10240
                minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
                deleteOriginalAssets: false // 删除原文件
            })
        )
    }

    // 代码压缩
    config.plugins.push(
      new UglifyJsPlugin({
          uglifyOptions: {
              //生产环境自动删除console
              compress: {
                  drop_debugger: true,
                  drop_console: true,
                  pure_funcs: ['console.log']
              }
          },
          sourceMap: false,
          parallel: true
      })
    )

    // 公共代码抽离
    config.optimization = {
      splitChunks: {
          cacheGroups: {
              vendor: {
                  chunks: 'all',
                  test: /node_modules/,
                  name: 'vendor',
                  minChunks: 1,
                  maxInitialRequests: 5,
                  minSize: 0,
                  priority: 100
              },
              common: {
                  chunks: 'all',
                  test: /[\\/]src[\\/]js[\\/]/,
                  name: 'common',
                  minChunks: 2,
                  maxInitialRequests: 5,
                  minSize: 0,
                  priority: 60
              },
              styles: {
                  name: 'styles',
                  test: /\.(sa|sc|c|l)ss$/,
                  chunks: 'all',
                  enforce: true
              },
              runtimeChunk: {
                  name: 'manifest'
              }
          }
      }
    }
  },

  chainWebpack: (config) => {
    // 配置路径别名
    config.resolve.alias
      .set("@", resolve("src"))
      .set("assets", resolve("src/assets"));
    
    // ============压缩图片 start============
    config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({ bypassOnDebug: true })
      .end()
    // ============压缩图片 end============

    // 开启js、css压缩
    if (process.env.NODE_ENV === 'production') {
      config.plugin('CompressionWebpackPlugin')
      .use(new CompressionWebpackPlugin({
        test:/\.js$|\.html$|.\css/, // 匹配文件名
        threshold: 10240, // 对超过10k的数据压缩
        deleteOriginalAssets: false // 不删除源文件
      }))
    }

    // ============分析打包后的文件结构 start============
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end()
        config.plugins.delete('prefetch')
      }
    }
    // ============分析打包后的文件结构 end============
  }
};